package org.btik.light.server.dev.manage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.app.tool.AsyncTaskExecutor;
import org.btik.light.meta.DevMo;
import org.btik.light.meta.base.video.VideoChannelType;
import org.btik.light.server.platform.common.api.dao.LightDao;
import org.btik.light.server.platform.common.api.service.OperationServer;
import org.btik.light.server.platform.common.api.bean.dev.manage.DevProp;
import org.btik.light.server.platform.manage.DevEventDispatcher;
import org.btik.light.meta.base.Command;
import org.btik.light.meta.base.DevRpcServer;
import org.btik.video.server.iface.DevChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 提供web操作管理功能<br>
 * 调度设备dev模块下发命令
 */
@Service
public class DevManageServer implements OperationServer {
    private final Log log = LogFactory.getLog(DevEventDispatcher.class);
    @Autowired
    private DevRpcServer rpcServer;

    @Autowired
    private LightDao lightDao;

    @Autowired
    private AsyncTaskExecutor devAsyncTaskExecutor;

    @Autowired
    private DevChannel deviceChannel;


    @Override
    public void sendCmdOrMsg(Command webCmd) {
        rpcServer.sendCmd(webCmd);
    }

    @Override
    public void sendAsyncCmdOrMsg(Command webCmd) {
        devAsyncTaskExecutor.execute(() -> rpcServer.sendCmd(webCmd));
    }

    @Override
    public Collection<DevMo> listAtNode(String node) {
        return lightDao.listAtNode(node);
    }

    @Override
    public Collection<DevMo> listCameraAtNode(String node) {
        return lightDao.listCameraAtNode(node);
    }

    @Override
    public boolean isOnLine(String sn) {
        return rpcServer.isOnline(sn);
    }

    @Override
    public boolean attachVideoChannel(VideoChannelType videoChannelType, int channelIndex, String devSn) {
        switch (videoChannelType) {
            case MJPEG -> deviceChannel.attachMjpegVideoChannel(channelIndex, devSn);
            case RAW_UDP -> deviceChannel.attachRawUDPVideoChannel(channelIndex, devSn);
        }
        return true;
    }

    @Override
    public boolean updateProp(DevProp devProp) {
        DevMo mo = lightDao.getMO(devProp.sn());
        if (mo == null) {
            return false;
        }
        mo.setExtendedAttribute(devProp.key(), devProp.value());
        return true;
    }

    @Override
    public DevMo getDevMo(String sn) {
        return lightDao.getMO(sn);
    }
}
